import * as fs from 'fs';
import path from 'path'
import * as step from '@flow-step/step-toolkit'

export type Pos = {
    Filename: string;
    Line: number;
    Column: number;
    Offset: number;
}


export type OriginIssue = {
    FromLinter: string;
    Text: string;
    Pos: Pos;
}

export type OriginIssueJson = {
    Issues: OriginIssue[];
    Report: string;
}

export type Issue = {
    ruleName: string;
    title: string;
    level: string;
    beginColumn: number;
    beginLine: number;
    endColumn: number;
    endLine: number;
    description: string;
    location: string;
}

export async function rewriteIssuesJson(originalIssuesPath: string, outputIssuesPath: string){
    const issueContent = fs.readFileSync(originalIssuesPath, 'utf-8');
    const issueOriginJSON: OriginIssueJson = JSON.parse(issueContent);
    const issueArray: Issue[] = issueOriginJSON.Issues.map(issue => ({
        ruleName: issue.FromLinter,
        title: issue.FromLinter,
        level: "BLOCKER",
        beginColumn: issue.Pos.Column,
        beginLine: issue.Pos.Line,
        endColumn: issue.Pos.Column + issue.Pos.Offset,
        endLine: issue.Pos.Line,
        description: issue.Text,
        location: issue.Pos.Filename
    }));

    const issueOutputJson = JSON.stringify(issueArray, null, 2);
    try {
        fs.writeFileSync(outputIssuesPath, issueOutputJson, 'utf-8');
    }catch (err){
        step.error(`Failed to rewrite issues.json`)
        throw err
    }
}